" AuthorInfo {{{
" File:   .bigvimrc
" Author: Guangsheng Li
" Date:   2019-03-08
" }}}


" Warning 
if v:version < 704
    echoerr "Your vim version is too low"
endif


" Functions
function! IsWindows()
    return has("win32")
endfunction

function! IsUnix()
    return has("unix")
endfunction


" Generic Settings
if &compatible
    set nocompatible
endif

" Coding
set encoding=utf-8
set fileencoding=utf-8
set fileencodings=utf-8,usc-bom,euc-jp,gb18030,gbk,gb2312,cp936
set termencoding=utf-8

" Chinese
set langmenu=zh_CN.UTF-8
language message zh_CN.UTF-8
source $VIMRUNTIME/delmenu.vim
source $VIMRUNTIME/menu.vim


" set autochdir                 " 自动cd到当前目录
set nocompatible
set backspace=indent,eol,start
set history=500
set confirm                     " 在处理未保存或只读文件的时候要求确认
set clipboard+=unnamed          " 共享剪切板
set nobackup                    " 不备份文件
set noswapfile                  " 不生成swap文件
set bufhidden=hide              " 当buffer被丢弃时隐藏
set linespace=1                 " 插入的像素行数目
set wildmenu                    " 增强模式中的命令自动完成操作
set whichwrap+=<,>,h,l          " 允许退格键和方向键跨越行边界
set shortmess=atl               " 不显示欢迎画面
set report=0                    " 报告哪一行被修改过
set noerrorbells                " 关闭警告声
set scrolloff=3                 " 移动时顶部和底部保持距离
set laststatus=2                " 总是显示状态行
set showcmd                     " 显示输入的命令
set autoread                    " 自动重新读入
set nu!                         " 显示行号
" set relativenumber            " 显示相对行号
" set cursorline                " 高亮当前行
" set cursorcolumn              " 高亮当前列
" set cc=80                     " 高亮第80列
set shellredir=>%s
syntax on                       " 打开语法高亮


" Complete
set complete=.,w,b,k,t,i
set completeopt=longest,menu


" Mouse
set mouse=a
set selection=exclusive
set selectmode=mouse,key


" Tab Page
set tabpagemax=8
set showtabline=1


" Line Number
set number
set ruler
set rulerformat=%15(%c%V\ %p%%%)


" Search and Match
set showmatch                  " 高亮显示匹配的括号
set matchtime=10               " 匹配括号高亮的时间（单位时十分之一秒）
set ignorecase                 " 搜索时忽略大小写
set nohlsearch                 " 不要高亮被搜索的片段
set incsearch                  " 搜索时输入的字符逐个高亮


" Text Format
set formatoptions=tcrqn        " 自动格式化
set autoindent                 " 继承前一行的缩进方式
set smartindent                " 智能的缩进
set cindent                    " 使用C样式的缩进
set tabstop=4                  " 制表符为4个空格
set softtabstop=4              " 缩进为4
set shiftwidth=4               " 缩进为4
set wrap                       " 自动换行
set expandtab                  " 插入模式使用空格代替tab 
set magic                      " 搜索模式使用特殊字符"
" set smarttab                 " 行和段开始处使用制表符
" set nofoldenable             " 不允许折叠
" set foldmethod=marker        " 折叠方式


" Keybindings
let g:mapleader = "\<Space>"
let g:maplocalleader = ','

nnoremap U   :redo<CR>
inoremap jk  <Esc>
inoremap kj  <Esc>
nnoremap <silent> zj o<ESC>k
nnoremap <silent> zk O<ESC>j
nnoremap J 5j
nnoremap K 5k
nnoremap <C-tab> :tabnext<CR>
" }}}

" Expand
iab vdate <c-r>=strftime("%Y-%m-%d %H:%M:%S")<CR>

" Plugins
call plug#begin('~/.vim/plugged')
Plug 'Chiel92/vim-autoformat'
Plug 'Konfekt/FastFold'
Plug 'Shougo/neosnippet-snippets'
Plug 'Shougo/neosnippet.vim'
Plug 'Shougo/unite.vim'
Plug 'Shougo/vimfiler.vim'
Plug 'easymotion/vim-easymotion'
Plug 'ervandew/supertab'
Plug 'honza/vim-snippets'
Plug 'jiangmiao/auto-pairs'
Plug 'junegunn/vim-easy-align'
Plug 'kien/rainbow_parentheses.vim'
Plug 'nathanaelkane/vim-indent-guides'
Plug 'scrooloose/nerdcommenter'
Plug 'tpope/vim-surround'
Plug 'vim-airline/vim-airline'
Plug 'vim-airline/vim-airline-themes'
Plug 'chriskempson/base16-vim'
Plug 'junegunn/seoul256.vim'
Plug 'sonph/onehalf', { 'rtp': 'vim' }
Plug 'junegunn/fzf', { 'do': { -> fzf#install() } }
Plug 'junegunn/fzf.vim'
Plug 'kien/ctrlp.vim'
call plug#end()

filetype plugin indent on

" Feature: airline {{{
" Require: 'vim-airline/vim-airline'
"          'vim-airline/vim-airline-themes'

" 允许airline运行
let g:airline#extensions#tabline#enabled = 1
if has('gui_running')
    let g:airline_powerline_fonts = 1
else
    let g:airline_powerline_fonts = 0
endif

if !exists('g:airline_symbols')
    let g:airline_symbols = {}
endif
" " unicode symbols
let g:airline_left_sep = '»'
let g:airline_left_sep = '▶'
let g:airline_right_sep = '«'
let g:airline_right_sep = '◀'
let g:airline_symbols.linenr = '␊'
let g:airline_symbols.linenr = '␤'
let g:airline_symbols.linenr = '¶'
let g:airline_symbols.branch = '⎇'
let g:airline_symbols.paste = 'ρ'
let g:airline_symbols.paste = 'Þ'
let g:airline_symbols.paste = '∥'
let g:airline_symbols.whitespace = 'Ξ'
"
" " airline symbols
" let g:airline_left_sep = ''
" let g:airline_left_alt_sep = ''
" let g:airline_right_sep = ''
" let g:airline_right_alt_sep = ''
let g:airline_symbols.branch = ''
let g:airline_symbols.readonly = ''
let g:airline_symbols.linenr = ''

" 设置airline主题
" https://github.com/vim-airline/vim-airline/wiki/Screenshots
" let g:airline_theme='deus'

" }}}

" Feature: Comment {{{
" Require: 'scrooloose/nerdcommenter'
" Usage: <leader>cc 注释当前行或者当前选区
"        <leader>cu 反注释选择的行
"        <leader>cn 跟cc相同，但是强制嵌套
"        <leader>c<space> 注释或反注释当前行，以选中的第一行为标准
"        <leader>ci 注释或反注释当前行，以每行的注释状态为标准
"        <leader>cs 注释成一个方块
"        <leader>cA 在行尾添加注释
"        <leader>c$ 从光标处注释到行尾

" 注释符号后面自动加上一个空格
let g:NERDSpaceDelims = 1

" Use compact syntax for prettified multi-line comments
let g:NERDCompactSexyComs = 1

" Align line-wise comment delimiters flush left instead of following code indentation
let g:NERDDefaultAlign = 'left'

" Set a language to use its alternate delimiters by default
let g:NERDAltDelims_java = 1

" 自定义注释格式
let g:NERDCustomDelimiters = { 'c': { 'left': '/**','right': '*/' } }

" Allow commenting and inverting empty lines (useful when commenting a region)
let g:NERDCommentEmptyLines = 1

" Enable trimming of trailing whitespace when uncommenting
let g:NERDTrimTrailingWhitespace = 1

" }}}

" Feature: Pairs {{{
" Require: 'kien/rainbow_parentheses.vim'
"          'jiangmiao/auto-pairs'
" Description: 彩虹括号，自动完成括号
" Usage: 按‘}’调到下一个‘}’处，使用M-b插入一个'}'
"        <CR>  : Insert new indented line after return if cursor in blank brackets or quotes.
"        <BS>  : Delete brackets in pair
"        <M-p> : Toggle Autopairs (g:AutoPairsShortcutToggle)
"        <M-e> : Fast Wrap (g:AutoPairsShortcutFastWrap)
"        <M-n> : Jump to next closed pair (g:AutoPairsShortcutJump)
"        <M-b> : BackInsert (g:AutoPairsShortcutBackInsert)

" 彩虹括号颜色设置
let g:rbpt_colorpairs = [
            \ ['brown',       'RoyalBlue3'],
            \ ['Darkblue',    'SeaGreen3'],
            \ ['darkgray',    'DarkOrchid3'],
            \ ['darkgreen',   'firebrick3'],
            \ ['darkcyan',    'RoyalBlue3'],
            \ ['darkred',     'SeaGreen3'],
            \ ['darkmagenta', 'DarkOrchid3'],
            \ ['brown',       'firebrick3'],
            \ ['gray',        'RoyalBlue3'],
            \ ['black',       'SeaGreen3'],
            \ ['darkmagenta', 'DarkOrchid3'],
            \ ['Darkblue',    'firebrick3'],
            \ ['darkgreen',   'RoyalBlue3'],
            \ ['darkcyan',    'SeaGreen3'],
            \ ['darkred',     'DarkOrchid3'],
            \ ['red',         'firebrick3'],
            \ ]
let g:rbpt_max = 16
let g:rbpt_loadcmd_toggle = 0

" 总是开启彩虹括号
"au VimEnter * RainbowParenthesesToggle
"au Syntax * RainbowParenthesesLoadRound
"au Syntax * RainbowParenthesesLoadSquare
"au Syntax * RainbowParenthesesLoadBraces

let g:AutoPairsFlyMode = 0
let g:AutoPairsShortcutBackInsert = '<M-b>'
" }}}

" Feature: Format {{{
" Require: 'Chiel92/vim-autoformat'
"          astyle.exe放在$VIM目录下
"          pip install yapf
"          npm install -g js-beautify
"          npm install -g remark
" Description: 格式化代码
" 格式化工具: see https://github.com/Chiel92/vim-autoformat

nnoremap <F8> :Autoformat<CR>

" 在写入文件时自动格式化
" au BufWrite * :Autoformat

let g:autoformat_autoindent = 1
let g:autoformat_retab = 1
let g:autoformat_remove_trailing_spaces = 1

" yapf格式化python风格，可选 pep8, google, facebook, chromium.
let g:formatter_yapf_style = 'pep8'

autocmd FileType vim,tex let b:autoformat_autoindent=1

" }}}

" Feature: Window Move {{{
" Require: <None>
" Description: 窗口跳转
" see :help window-moving

nmap <silent> <A-Up> :wincmd k<CR>
nmap <silent> <A-Down> :wincmd j<CR>
nmap <silent> <A-Left> :wincmd h<CR>
nmap <silent> <A-Right> :wincmd l<CR>
" }}}

" Feature: File Explorer {{{
" Require:   'Shougo/vimfiler.vim'
"            'Shougo/unite.vim'
"            'mattn/vimfiler-icon'
" Description: 文件浏览器

nmap <F2> :VimFilerExplorer<CR>

" }}}

" Feature: Snippets {{{
" Require: 'Shougo/neosnippet.vim'
"          'Shougo/neosnippet-snippets'
"          'honza/vim-snippets'
" Description: 代码片段
" Usage: <C-k> 展开代码片段
"         插入模式下Tab键也可以展开代码片段

imap <C-k>     <Plug>(neosnippet_expand_or_jump)
smap <C-k>     <Plug>(neosnippet_expand_or_jump)
xmap <C-k>     <Plug>(neosnippet_expand_target)

imap <expr><TAB>
            \ pumvisible() ? "\<C-n>" :
            \ neosnippet#expandable_or_jumpable() ?
            \    "\<Plug>(neosnippet_expand_or_jump)" : "\<TAB>"
smap <expr><TAB> neosnippet#expandable_or_jumpable() ?
            \ "\<Plug>(neosnippet_expand_or_jump)" : "\<TAB>"

if has('conceal')
    set conceallevel=2 concealcursor=niv
endif

let g:neosnippet#snippets_directory=expand('$VIM/vimfile/dein/repos/github.com/honza/vim-snippets/snippets')

" }}}

" Feature: Complete {{{
" Require: 'ervandew/supertab'
" }}}

" Feature: Fold {{{
" Require:'Konfekt/FastFold'
" Description: 折叠

" Feature: easymotion {{{
" Require: 'easymotion/vim-easymotion'
" Description: 快速移动
" Usage: <leader><leader>w 向下跳转到单词首字母
"         <leader>f{char} 移动到{char}
"         s 移动到两个char
"         <leader>L 行间跳跃
"         <leader>w 单词间跳跃
"         <leader>[hjkl] 行间跳跃

map  <Leader>f <Plug>(easymotion-bd-f)
nmap <Leader>f <Plug>(easymotion-overwin-f)

nmap s <Plug>(easymotion-s2)
nmap t <Plug>(easymotion-t2)

map <Leader>L <Plug>(easymotion-bd-jk)
nmap <Leader>L <Plug>(easymotion-overwin-line)

map  <Leader>w <Plug>(easymotion-bd-w)
nmap <Leader>w <Plug>(easymotion-overwin-w)

map <Leader>l <Plug>(easymotion-lineforward)
map <Leader>j <Plug>(easymotion-j)
map <Leader>k <Plug>(easymotion-k)
map <Leader>h <Plug>(easymotion-linebackward)

let g:EasyMotion_startofline = 0 " keep cursor column when JK motion

" }}}

" Feature: unite.vim {{{
" Require: 'Shougo/unite.vim'
" Description: 快速浏览插件
" Usage: <leader>bb buffer切换
"         <M-x> 执行命令

nnoremap <leader>bb :Unite -start-insert buffer<CR>
nnoremap <leader>ff :Unite -start-insert file<CR>
nnoremap <C-p> :Unite file_rec/async<CR>
nnoremap <space>w :<C-u>Unite window<CR>
noremap <M-x> :<C-u>Unite -start-insert command<CR>

" }}}

" Feature: vim-easy-align {{{
" Require: 'junegunn/vim-easy-align'
" Description: 快速对齐

xmap ga <Plug>(EasyAlign)
nmap ga <Plug>(EasyAlign)

" }}}

" Feature: surround {{{
" Require: tpope/vim-surround
" Usage: see :help surround
" }}}

" UI
if has("gui_running")
    set guioptions-=T " remove toolbar
    set guioptions-=m " remove menubar
    set guioptions-=r " remove right-hand scroll bar
    set guioptions-=L " remove left-hand scroll bar
    set background=dark
    " seoul256 (dark):
    "   Range:   233 (darkest) ~ 239 (lightest)
    "   Default: 237
    let g:seoul256_background = 235
    " seoul256 (light):
    "   Range:   252 (darkest) ~ 256 (lightest)
    "   Default: 253
    let g:seoul256_light_background = 256
    autocmd GUIEnter * simalt ~x
    autocmd VimEnter * colorscheme seoul256

    " 设置gui字体
    if has("win32")
        set guifont=Source\ Code\ Pro\ for\ Powerline:h10,consolas:h10
    elseif has("unix")
        set guifont=Source\ Code\ Pro\ for\ Powerline:h10,Monaco:h10
    endif

else
    set t_Co=256
    set termguicolors
    let base16colorspace=256
    let g:seoul256_background = 233
    try
        colorscheme seoul256
    catch /^Vim\%((\a\+)\)\=:E185/
        colorscheme default
    endtry
endif

if &term =~ '^xterm'
    " enter vim
    autocmd VimEnter * silent !echo -ne "\e[1 q"
    " oherwise
    let &t_EI .= "\<Esc>[1 q"
    " insert mode
    let &t_SI .= "\<Esc>[6 q"
    " 1 or 0 -> blinking block
    " 2 -> solid block
    " 3 -> blinking underscore
    " 4 -> solid underscore
    " Recent versions of xterm (282 or above) also support
    " 5 -> blinking vertical bar
    " 6 -> solid vertical bar
    " leave vim
    autocmd VimLeave * silent !echo -ne "\e[5 q"
endif

